﻿using Shake.Business.Infrastructures;
using Shake.Domain.Models;
using Shake.Framework.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shake.Business.Services
{
    public class PostInfoService : IPostInfoService
    {
        public IRepository _repository { get; set; }
        public PostInfo GetEntity(string id)
        {
            using (var factory = _repository.CreateSessionFactory())
            {
                var session = factory.GetCurrentSession();
                var query = session.QueryOver<PostInfo>();

                var entity = query.Where(t => t.Id == id).List();
                if (entity.Count == null) return null;
                return entity.FirstOrDefault();
            }
        }
        public void Save(PostInfo entity)
        {
            if (entity == null) throw new Exception("参数异常");
            if (string.IsNullOrEmpty(entity.Id))
            {
                entity.Id = Guid.NewGuid().ToString("N");
                entity.CreateUser = "Admin";
                entity.CreateDate = DateTime.Now;
                entity.UpdateUser = "Admin";
                entity.UpdateDate = DateTime.Now;
                _repository.Insert(entity);
            }
            else
            {
                var oEntity = GetEntity(entity.Id);
                oEntity.PostName = entity.PostName;
                oEntity.Remark = entity.Remark;
                oEntity.UpdateUser = "Admin";
                oEntity.UpdateDate = DateTime.Now;
                _repository.Update(oEntity);
            }            
        }

        public void Remove(List<PostInfo> entitys)
        {
            if (entitys == null) return;
            _repository.DeleteMany(entitys);
        }

        public List<PostInfo> GetAll()
        {
            using (var factory = _repository.CreateSessionFactory())
            {
                var session = factory.GetCurrentSession();
                var query = session.QueryOver<PostInfo>();                
                var results = query.List();
                return results.ToList();
            }
        }
    }
}
